package org.cboard.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.cboard.dto.User;
import org.cboard.security.service.DbUserDetailService;
import org.cboard.security.token.TokenUtils;
import org.cboard.services.ServiceStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;

@Controller
public class LoginController {
	public static final String SESSION_LOGIN_USER = "sys_login_user";

	@Autowired
	private DbUserDetailService dbUserDetailService;

	@RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST })
	public String loginPage() {
		return "login";
	}

	/**
	 * 管理登录
	 */
	@RequestMapping(value = "/sysLogin", method = { RequestMethod.POST })
	public String login(HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		String password = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM);
		if (password == null) {
			password = "";
		}
		boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray(), rememberMe);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			SecurityUtils.getSubject().getSession().setAttribute(LoginController.SESSION_LOGIN_USER,
					dbUserDetailService.loadUserByUsername(username));
			return "redirect:/starter.html#/home";
		} catch (Exception e) {
			if (e instanceof IncorrectCredentialsException) {
				redirectAttributes.addFlashAttribute("message", "用户名或密码不正确！");
			}
			e.printStackTrace();
			return "redirect:/login.html";
		}

	}

	/**
	 * 管理登录
	 * 
	 * 成功后： return "redirect:/starter.html#/home"; 失败后：return
	 * "redirect:/login.html";
	 */
	@RequestMapping(value = "/ajaxLogin", method = { RequestMethod.POST })
	@ResponseBody
	public ServiceStatus ajaxLogin(HttpServletRequest request) {
		String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		String password = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM);
		if (password == null) {
			password = "";
		}
		boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray(), rememberMe);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			SecurityUtils.getSubject().getSession().setAttribute(LoginController.SESSION_LOGIN_USER,
					dbUserDetailService.loadUserByUsername(username));
			return new ServiceStatus(ServiceStatus.Status.Success, "success");
		} catch (Exception e) {
			if (e instanceof IncorrectCredentialsException) {
				return new ServiceStatus(ServiceStatus.Status.Fail, "用户名或密码不正确！");
			}
			e.printStackTrace();
		}
		return new ServiceStatus(ServiceStatus.Status.Close, "用户名或密码不正确！");
	}

	public User getActivitySessionUser() {
		return (User) SecurityUtils.getSubject().getSession().getAttribute(LoginController.SESSION_LOGIN_USER);
	}

	@RequestMapping(value = "/logout")
	public String logout() {
		SecurityUtils.getSubject().getSession().removeAttribute(LoginController.SESSION_LOGIN_USER);
		SecurityUtils.getSubject().logout();
		return "redirect:/login.html";
	}

	@RequestMapping(value = "/publicUrl", method = RequestMethod.GET)
	public String publicUrl(@RequestParam("token") String token) throws Exception {

		StringBuilder sb = new StringBuilder("/viewDetail.html?id=");
		JSONObject object = TokenUtils.parseToken(token);
		sb.append(object.get("boardId")).append("&token=").append(token).append("&theme=").append(object.get("theme"));
		return sb.toString();
	}

	private String getPrincipal() {
		String userName = null;
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		if (principal instanceof UserDetails) {
			userName = ((UserDetails) principal).getUsername();
		} else {
			userName = principal.toString();
		}
		return userName;
	}

}